package com.sandwich.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.sandwich.admin.apibean.CommentInfo;
import com.sandwich.admin.apibean.CommentRequest;
import com.sandwich.admin.domain.CommentEntity;
import com.sandwich.admin.domain.ContentSummaryEntity;
import com.sandwich.admin.domain.repository.ContentSummaryRepository;
import com.sandwich.admin.service.CommentService;
import com.sandwich.api.apibean.v1.ContentDetailRequest;
import com.sandwich.admin.service.ContentDetailService;
import com.sandwich.api.apibean.v1.ContentSummary;
import com.sandwich.api.apibean.v1.ContentSummaryDetail;
import com.sandwich.api.apibean.v1.ContentSummaryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ContentDetailServiceImpl implements ContentDetailService {
    @Autowired
    private ContentSummaryRepository contentSummaryRepository;
    @Autowired
    private CommentService commentService;

    @Override
    public ContentSummaryDetail getContentDetail(ContentDetailRequest contentDetailRequest) {
        int currentPage = contentDetailRequest.getCurrentPage();
        int pageSize = contentDetailRequest.getPageSize();
        long contentSummaryPk = contentDetailRequest.getContentSummaryPk();
        long parentPk = contentDetailRequest.getParentPk();

        ContentSummaryDetail contentSummaryDetail = new ContentSummaryDetail();
        //第一屏要取summary
        if (currentPage == 1 && contentSummaryPk > 0) {
            ContentSummaryEntity entity = contentSummaryRepository.findById(contentSummaryPk).get();
            ContentSummary contentSummary = JSON.parseObject(entity.getContentJson(), ContentSummary.class);
            ContentSummaryDto detailDto = new ContentSummaryDto(entity.getPk(), contentSummary.getTitle(), entity.getPicture(), entity.getVideoUrl(), contentSummary.getCoverUrl());
            contentSummaryDetail.setContentSummaryDto(detailDto);
        }

        //获取评论信息
        CommentRequest commentRequest = new CommentRequest();
        commentRequest.setContentSummaryPk(contentSummaryPk);
        commentRequest.setParentPk(parentPk);
        commentRequest.setCurrentPage(currentPage);
        commentRequest.setPageSize(pageSize);
        Page<CommentEntity> commentEntityPage = commentService.queryCommentEntity(commentRequest);


        List<CommentEntity> contents = commentEntityPage.getContent();
        List<CommentInfo> commentInfos = contents.stream().map(x -> new CommentInfo(x)).collect(Collectors.toList());
        contentSummaryDetail.setCommments(commentInfos);
        contentSummaryDetail.setTotalPage(commentEntityPage.getTotalPages());
        return contentSummaryDetail;
    }
}
